package com.sam.im.heiqun.utils;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.CircleEntivity;
import com.sam.im.heiqun.entities.CircleNums;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImGroupEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.ImageSendEntity;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.TipEntity;
import com.sam.im.heiqun.entities.UserEntivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by Joe on 2017/1/8.
 */

public class IMMessageToJson {

    private Long id;
    private Integer version;
    private Integer devType;
    private Integer geoId;
    private String msgId;
    private Long fromId;
    private Integer fromType;
    private Long destId;
    private String message;
    private Integer messageType;
    private Long sendTime;
    private Long receiveTime;
    private Integer status;

    /**
     * 将聊天消息对象转换成json数据
     *
     * @param imMessage
     * @return
     */
    public static JSONObject changeJSONObject(ImMessage imMessage) {
        JSONObject jsonObject = new JSONObject();
        if (imMessage == null)
            return null;
        try {
            jsonObject.put("version", imMessage.getVersion() + "");
            jsonObject.put("devType", imMessage.getDevType() + "");
            jsonObject.put("geoId", imMessage.getGeoId() + "");
            jsonObject.put("msgId", imMessage.getMsgId() + "");
            jsonObject.put("fromId", imMessage.getFromid() + "");
            jsonObject.put("fromType", imMessage.getFromType() + "");
            jsonObject.put("destId", imMessage.getDestid() + "");
            jsonObject.put("content", imMessage.getContent() + "");
            jsonObject.put("messageType", imMessage.getMessageType() + "");
            jsonObject.put("sendTime", imMessage.getSendTime() + "");
            jsonObject.put("receiveTime", imMessage.getReceiveTime() + "");
            jsonObject.put("status", imMessage.getStatus() + "");
            jsonObject.put("imageIconUrl", imMessage.getImageIconUrl() + "");
            jsonObject.put("fromName", imMessage.getFromname() + "");
            return jsonObject;
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 将json数据转化成聊天消息对象
     *
     * @param str
     * @return
     */
    public static ImMessage jsonToImMessage(String str) {
        JSONObject jsonObject = null;
        ImMessage imMessage = new ImMessage();
        try {
            jsonObject = new JSONObject(str);
            int messageType = jsonObject.optInt("messageType");
            imMessage.setMessageType(messageType);
            imMessage.setDestid(jsonObject.optLong("fromId"));
            imMessage.setFromid(jsonObject.optLong("destId"));
            imMessage.setFileUrl(jsonObject.optString("fileUrl"));
            imMessage.setVersion(jsonObject.optInt("version"));
            imMessage.setGeoId(jsonObject.optInt("geoId"));
            imMessage.setMsgId(jsonObject.optString("msgId"));
            imMessage.setFromType(jsonObject.optInt("fromType"));
            String content = jsonObject.optString("content");
            if ("null".equals(content)) {
                content = "null ";
            }
            imMessage.setContent(content);
            imMessage.setUserVoicePath(jsonObject.optString("content"));
            if (messageType == Constant.MESSAGE_TYPR_IMAGE) {
                ImageSendEntity imageSendEntity = JsonUtil.toObject(content, ImageSendEntity.class);
                if (imageSendEntity != null) {
                    imMessage.setFileUrl(imageSendEntity.getImagePath());
                }
            } else {
                imMessage.setFileUrl(jsonObject.optString("content"));
            }
            imMessage.setUserVoicePath(jsonObject.optString("content"));

            imMessage.setSendTime(jsonObject.optLong("sendTime"));
            imMessage.setReceiveTime(jsonObject.optLong("receiveTime"));
            imMessage.setStatus(jsonObject.optInt("status"));
            imMessage.setImageIconUrl(jsonObject.optString("imageIconUrl"));//每条消息的头像
            imMessage.setFromname(jsonObject.optString("fromName"));//每条消息的名称

            if (imMessage.getFromType() == Constant.FROM_TYPE_MAM) {
                imMessage.setUniqueness(imMessage.getFromid() + "_" + imMessage.getDestid());

            } else if (imMessage.getFromType() == Constant.FROM_TYPE_GROUP || (imMessage.getFromType() == Constant.FROM_TYPE_SYS && Constant.MESSAGE_TYPR_ADD_GROUP == imMessage.getMessageType())) {

                UserEntivity userEntivity = ToolsUtils.getUser();
                if (Constant.MESSAGE_TYPE_BE_JOIN_GROUP == imMessage.getMessageType()) {
                    imMessage.setUniqueness(userEntivity.getId() + "__" + imMessage.getDestid());
                } else {
                    imMessage.setUniqueness(userEntivity.getId() + "__" + imMessage.getFromid());
                }
            } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME
                    | imMessage.getMessageType() == Constant.MESSAGE_TYPR_TOPAYFOR
                    | imMessage.getMessageType() == Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP
                    | imMessage.getMessageType() == Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP) {
                UserEntivity userEntivity = ToolsUtils.getUser();
                imMessage.setUniqueness(userEntivity.getId() + "___");
            }

            if (Constant.MESSAGE_TYPR_REDPACKET_BACK == imMessage.getMessageType()) {
                imMessage.setFromid(imMessage.getDestid());//红包返回处理一下
                ImFriendEntivity self = ToolsUtils.getUser();
                imMessage.setUniqueness(self.getId() + "__" + imMessage.getDestid());
            }
            ImFriendEntivity imFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, imMessage.getDestid());
            //Log.i("-----", "jsonToImMessage: getUniqueness=" + imMessage.getUniqueness());
            if (imFriendEntivity != null) {
//                imMessage.setImageIconUrl(imFriendEntivity.getHeadUrl());
            }
            return imMessage;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将聊天信息对象转化成消息界面消息对象
     *
     * @return
     */
    public static synchronized MessageEntivity ImMessageToMessageEntivity(ImMessage imMessage, int fromtype) {
        MessageEntivity messageEntivity = new MessageEntivity();
        messageEntivity.setType(imMessage.getMessageType());//聊天类型
        messageEntivity.setContent(imMessage.getContent());
        messageEntivity.setFromType(imMessage.getFromType());
        messageEntivity.setNick(imMessage.getFromname());
        messageEntivity.setFromtype(fromtype);
        if (imMessage.getReceiveTime() != null && imMessage.getReceiveTime() != 0) {
            messageEntivity.setTime(imMessage.getReceiveTime());//时间序号出来
        } else {
            messageEntivity.setTime(imMessage.getSendTime());//时间序号出来
        }

        //设置消息置顶
        if (imMessage.getFromType() == Constant.FROM_TYPE_MAM)//私聊
        {
            messageEntivity.setFromid(imMessage.getFromid());//也是自己的id
            messageEntivity.setDestid(imMessage.getDestid());
            messageEntivity.setUniqueness("_");//一个下滑线
        } else if (imMessage.getFromType() == Constant.FROM_TYPE_GROUP) {//群聊用自己的id設置成群的fromid
            UserEntivity userEntivity = ToolsUtils.getUser();
            messageEntivity.setFromid(userEntivity.getId());
            if (messageEntivity.getFromtype() == Constant.FROM_TYPE_SELF) {
                messageEntivity.setDestid(imMessage.getDestid());
            } else {
                messageEntivity.setDestid(imMessage.getFromid());
            }
            if (Constant.MESSAGE_TYPR_REDPACKET_BACK == imMessage.getMessageType()) {
                messageEntivity.setDestid(imMessage.getDestid());//红包返回处理一下
            }
            messageEntivity.setUniqueness("__");//两个下划线
        } else if ((imMessage.getFromType() == Constant.FROM_TYPE_SYS)) {
            //Log.i("info","系统消息  fromid="+imMessage.getFromid()+" destid=="+imMessage.getDestid());
            if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME) {
                messageEntivity.setDestid(imMessage.getFromid());
                messageEntivity.setFromid(Long.parseLong(ToolsUtils.getMyUserId()));//也是自己的id
            } else if (imMessage.getMessageType() == Constant.MESSAGE_GROUP_ADD_APPLY) {//接收到加群申请，需要处理
                //群ID在content中获取
                messageEntivity.setDestid(imMessage.getDestid());//申请人ID
                messageEntivity.setFromid(Long.parseLong(ToolsUtils.getMyUserId()));//也是自己的id
            } else {
                messageEntivity.setFromid(imMessage.getFromid());//也是自己的id
                messageEntivity.setDestid(imMessage.getDestid());
            }

            if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME
                    | imMessage.getMessageType() == Constant.MESSAGE_TYPR_TOPAYFOR
                    | imMessage.getMessageType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME
                    | imMessage.getMessageType() == Constant.MESSAGE_GROUP_ADD_APPLY
                    | imMessage.getMessageType() == Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP
                    | imMessage.getMessageType() == Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP
                    ) {
                Log.i("info", "进入了===");
                UserEntivity userEntivity = ToolsUtils.getUser();
                messageEntivity.setUniqueness(userEntivity.getId() + "___");
            } else {
                messageEntivity.setUniqueness("___");//三个下划线
            }
        }
        setTop(messageEntivity);
        ImFriendEntivity imFriendEntivity = ToolsUtils.getFriendById("" + messageEntivity.getDestid());
//                IMSharedPreferences.getsaveReadyEntivity().getIdFriendsInfo(messageEntivity.getDestid());
        if (imFriendEntivity != null) {
            String nick = ToolsUtils.getNick(imFriendEntivity);
            messageEntivity.setNick(nick);
            messageEntivity.setImgUrl(imFriendEntivity.getHeadUrl());
        }
        List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class
                , "fromid=? and destid=? and uniqueness =? and type!=? and type!=? and type!=? and type!=? and type!=? and type!=?",
                String.valueOf(messageEntivity.getFromid()),
                messageEntivity.getDestid() + "",
                messageEntivity.getUniqueness(),
                Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + "",
                Constant.MESSAGE_TYPR_TOPAYFOR + "",
                Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "",
                Constant.MESSAGE_GROUP_ADD_APPLY + "",
                Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP + "",
                Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP + "");
        if (messageEntivities.size() > 0 && imMessage.getMessageType() != Constant.MESSAGE_TYPR_TRANSFOR_ISCOME
                && imMessage.getMessageType() != Constant.MESSAGE_TYPR_TOPAYFOR
                && imMessage.getMessageType() != Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP
                && imMessage.getMessageType() != Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP) {//已经有相同id的消息 支付消息除外
            MessageEntivity old = messageEntivities.get(0);
            old.setContent(messageEntivity.getContent());
            long num = old.getMessageNum();
            Log.i("info", "type==" + messageEntivity.getFromtype());
            if (messageEntivity.getFromtype() == Constant.FROM_TYPE_OTHER) {
                String content = "";
                if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_IMAGE) {
                    content = "[图片]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TEXT
                        | imMessage.getMessageType() == Constant.MESSAGE_TYPR_APPLY_FRIEND
                        | imMessage.getMessageType() == Constant.MESSAGE_TYPR_BQEMOJI
                        | imMessage.getMessageType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME
                        | imMessage.getMessageType() == Constant.MESSAGE_GROUP_ADD_APPLY
                        | imMessage.getMessageType() == Constant.MESSAGE_TYPE_BE_JOIN_GROUP
                        | imMessage.getMessageType() == Constant.NOTICE_OF_APPLY_FRIEND
                        ) {
                    content = imMessage.getContent();
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_ADD_GROUP) {
                    content = "[有人加入了群]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_VOICE) {
                    content = "[语音]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_LOCATION) {
                    content = "[位置]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_REDPACKET_BACK) {
                    content = "[您的红包被退还]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFRE_BACK) {
                    content = "[您的转账被退还]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFRE_OK) {
                    content = "[您的转账被领取]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_GET_REDPACKET) {
                    content = "[您的红包被领取]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFRE) {
                    content = "[转账]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_REDPACKTE) {
                    content = "[红包]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_WITHDRAW) {//撤回消息
                    // content = "\""+imMessage.getFromname()+"\""+"撤回了一条消息";
                    content = "[撤回了一条消息]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_FILE) {//文件
                    content = "[文件]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_VEDIO) {//小视屏
                    content = "[小视屏]";
                /*}else if (imMessage.getMessageType()==Constant.MESSAGE_TYPR_TRANSFOR_ISCOME){
                    content = "[收款]";*/
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
                    content = "[付款]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_AAMONEY_GET) {
                    content = "[AA收款]";
                } else if (imMessage.getMessageType() == Constant.Someone_initiated_the_lucky_red_envelope) {
                        content = "[幸运红包]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_READ_DELETE) {
                    content = "[阅后即焚]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPE_INVATE_JOIN_GROUP) {
                    content = "[邀请你加入群聊]";
                }
                old.setContent(content);
                //消息免打扰的判断（红点）
                if (imMessage.getFromType() == Constant.FROM_TYPE_MAM)//私聊
                {
                    ImFriendEntivity myimFriend = ImFriendEntivity.findById(ImFriendEntivity.class, imMessage.getDestid());
                    if (myimFriend == null || !"0".equals(myimFriend.getReceiveTip())) {
                        num++;
                        old.setMessageNum(num);
                        ToolsUtils.notification(imMessage, content);
                    }
                } else if (imMessage.getFromType() == Constant.FROM_TYPE_GROUP) {//群聊用自己的id設置成群的fromid???什么鬼
                    Log.i("info", "ImMessageToMessageEntivity: ============imMessage.getFromid()=" + imMessage.getFromid());
                    ImGroupEntivity myimGroup = ImGroupEntivity.findById(ImGroupEntivity.class, imMessage.getFromid());
                    Log.i("info", "ImMessageToMessageEntivity: ======0001=======");
                    if (myimGroup != null && myimGroup.getReceiveTip() != null && Constant.ACCEPT_MSG != myimGroup.getReceiveTip()) {
                        Log.i("info", "ImMessageToMessageEntivity: ======0002=======" + num);
                        num++;
                        Log.i("info", "ImMessageToMessageEntivity: ======0003=======" + num);
                        old.setMessageNum(num);
                        if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_REDPACKTE||imMessage.getMessageType() == Constant.Someone_initiated_the_lucky_red_envelope) {//红包
                            if (!("" + imMessage.getDestid()).equals(ToolsUtils.getMyUserId())) {
                                //只有不是我发的红包才会有可能在状态栏有提示
                                ToolsUtils.notification(imMessage, content);
                            }
                        } else {
                            ToolsUtils.notification(imMessage, content);
                        }
                    }
                } else if (imMessage.getFromType() == Constant.FROM_TYPE_SYS) {//系统消息
                    // Log.i("info","FROM_TYPE_SYS接收到系统消息");
                    num++;
                    old.setMessageNum(num);
                    ToolsUtils.notification(imMessage, content);
                }
            }
            old.setFromType(Constant.FROM_TYPE_OTHER);
            old.setType(messageEntivity.getType());//聊天类型
            old.setFromtype(fromtype);
            old.setImgUrl(messageEntivity.getImgUrl());
            old.setFromType(messageEntivity.getFromType());
            old.setNick(messageEntivity.getNick());
            old.setTime(messageEntivity.getTime());
            old.setIstop(messageEntivity.getIstop());

            if (imMessage.getFromType() == Constant.FROM_TYPE_MAM)//私聊
            {
                old.setFromid(imMessage.getFromid());//也是自己的id
                old.setDestid(imMessage.getDestid());
                old.setUniqueness(messageEntivity.getUniqueness());
            } else if (imMessage.getFromType() == Constant.FROM_TYPE_GROUP) {//群聊用自己的id設置成群的fromid
                ImFriendEntivity self = ToolsUtils.getUser();
                old.setFromid(self.getId());
                if (messageEntivity.getFromtype() == Constant.FROM_TYPE_SELF) {
                    Log.i("info", "发送的消息 id= " + imMessage.getFromid() + "destid==" + imMessage.getDestid());
                    old.setDestid(imMessage.getDestid());
                } else {
                    old.setDestid(imMessage.getFromid());
                }

                old.setUniqueness(messageEntivity.getUniqueness());
            }
         /*  else if (imMessage.getFromType() == Constant.FROM_TYPE_SYS) {//系统
              ImFriendEntivity self = IMSharedPreferences.getSelfImFriendEntivity();
               old.setFromid(imMessage.getFromid());//也是自己的id
              old.setDestid(imMessage.getDestid());
               old.setUniqueness(messageEntivity.getUniqueness());
           }*/
            MessageEntivity.save(old);
        } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFOR_ISCOME
                | imMessage.getMessageType() == Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP
                | imMessage.getMessageType() == Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP
                | imMessage.getMessageType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
            List<MessageEntivity> sysList2 = MessageEntivity.find(MessageEntivity.class, "type in(?,?,?,?)",
                    new String[]{Constant.MESSAGE_TYPR_TRANSFOR_ISCOME + "",
                            Constant.MESSAGE_TYPR_TOPAYFOR + "",
                            Constant.NOTICE_OF_MONEY_ADD_FOR_JOIN_GROUP+"",
                            Constant.NOTICE_OF_MONEY_REDUCE_JOIN_GROUP+""}, null, "time desc", null);
            Log.i("info", "mesagesize==" + sysList2.size());
            if (sysList2.size() > 0) {
                MessageEntivity messageEntivity1 = sysList2.get(0);
                long messageNum = messageEntivity1.getMessageNum();
                messageNum++;
                messageEntivity1.setMessageNum(messageNum);
                messageEntivity1.setType(imMessage.getMessageType());
                messageEntivity1.setUniqueness(ToolsUtils.getMyUserId() + "___");
                MessageEntivity.save(messageEntivity1);
            } else {
                messageEntivity.setMessageNum(1);
                messageEntivity.save();
            }
            ToolsUtils.notification(imMessage, "您有一笔款项到账");
//        }else if (imMessage.getMessageType()==Constant.MESSAGE_TYPR_GROUP_TRANS_ME){
//            //MESSAGE_GROUP_ADD_APPLY
//            List<MessageEntivity> sysList2 = MessageEntivity.find(MessageEntivity.class
//                    , "type=? ", new String[]{Constant.MESSAGE_TYPR_GROUP_TRANS_ME + ""}, null, "time desc", null);
//            Log.i("info","mesagesize=="+sysList2.size());
//            boolean isHave = false ;
//            if (sysList2.size()>0){
//                MessageEntivity messageEntivity1 = sysList2.get(0);
//                long messageNum = messageEntivity1.getMessageNum();
//            Log.i("info","mesagesize====开始是多少====messageNum="+messageNum);
//                com.alibaba.fastjson.JSONObject json = JSON.parseObject(imMessage.getContent());
//                String groupId = json.getString("groupId");
////                if (0 == messageNum){
////                    messageNum++ ;
////                }else {
//                    Log.i("info","mesagesize====开始是多少====groupId="+ groupId);
//                    List<MessageEntivity> messageEntivitiesm  = MessageEntivity.find(MessageEntivity.class, "fromid = ? and type = ? "
//                            , new String[]{ToolsUtils.getMyUserId() + "", Constant.MESSAGE_TYPR_GROUP_TRANS_ME + ""});
//
//                    if (null!=messageEntivitiesm && messageEntivitiesm.size() > 0){
//                        Log.i("info","mesagesize====开始是多少====messageEntivitiesm.size()="+messageEntivitiesm.size());
//                        for (int i = 0; i < messageEntivitiesm.size(); i++) {
//                            MessageEntivity msg = messageEntivitiesm.get(i);
//                            Log.i("info","mesagesize====开始是多少====msg.getDestid()="+ msg.getDestid());
//
//                            if ((""+msg.getDestid()).equals(groupId)){
//                                Log.i("info","mesagesize====开始是多少====isHave="+ true);
//                                isHave = true ;
//                            }
//                        }
//                        if (!isHave){
//                            messageNum++ ;
//                        }
//
//                        EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
//                    }
////                }
////                messageEntivity1.setDestid(Long.parseLong(groupId));
//                messageEntivity1.setMessageNum(messageNum);
//                messageEntivity1.setType(imMessage.getMessageType());
//                messageEntivity1.setUniqueness(ToolsUtils.getMyUserId()+"___");
//                MessageEntivity.save(messageEntivity1);
//            }else {
//                messageEntivity.setMessageNum(1);
//            }
//            if (!isHave){
//                messageEntivity.save();
//            }
        } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME || imMessage.getMessageType() == Constant.MESSAGE_GROUP_ADD_APPLY) {
            //MESSAGE_GROUP_ADD_APPLY
            List<MessageEntivity> sysList2 = MessageEntivity.find(MessageEntivity.class
                    , "type=? or type=?", new String[]{Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "", Constant.MESSAGE_GROUP_ADD_APPLY + ""}, null, "time desc", null);
            Log.i("info", "mesagesize==" + sysList2.size());
            boolean isHave = false;
            if (sysList2.size() > 0) {
                MessageEntivity messageEntivity1 = sysList2.get(0);
                long messageNum = messageEntivity1.getMessageNum();
                Log.i("info", "mesagesize====开始是多少====messageNum=" + messageNum);
                com.alibaba.fastjson.JSONObject json = JSON.parseObject(imMessage.getContent());
                String groupId = json.getString("groupId");
//                if (0 == messageNum){
//                    messageNum++ ;
//                }else {
                Log.i("info", "mesagesize====开始是多少====groupId=" + groupId);
                List<MessageEntivity> messageEntivitiesm = MessageEntivity.find(MessageEntivity.class,
                        "fromid = ? and (type = ? or type=?)",
                        ToolsUtils.getMyUserId() + "",
                        Constant.MESSAGE_TYPR_GROUP_TRANS_ME + "",
                        Constant.MESSAGE_GROUP_ADD_APPLY + "");

                if (null != messageEntivitiesm && messageEntivitiesm.size() > 0) {
                    Log.i("info", "mesagesize====开始是多少====messageEntivitiesm.size()=" + messageEntivitiesm.size());
                    for (int i = 0; i < messageEntivitiesm.size(); i++) {
                        MessageEntivity msg = messageEntivitiesm.get(i);
                        Log.i("info", "mesagesize====开始是多少====msg.getDestid()=" + msg.getDestid());

                        if (("" + msg.getDestid()).equals(groupId)) {
                            Log.i("info", "mesagesize====开始是多少====isHave=" + true);
                            isHave = true;
                        }
                    }
                    if (!isHave) {
                        messageNum++;
                    }

                    EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                }
//                }
//                messageEntivity1.setDestid(Long.parseLong(groupId));
                messageEntivity1.setMessageNum(messageNum);
                messageEntivity1.setType(imMessage.getMessageType());
                messageEntivity1.setUniqueness(ToolsUtils.getMyUserId() + "___");
                MessageEntivity.save(messageEntivity1);
            } else {
                messageEntivity.setMessageNum(1);
            }
            if (!isHave) {
                messageEntivity.save();
            }
        } else {//第一次收到
            Log.i("info", "mesagesize===第一次收到==");
            messageEntivity.setMessageNum(1);
            messageEntivity.save();
            if (messageEntivity.getFromtype() == Constant.FROM_TYPE_OTHER) {
                String contentnew = "";
                if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_IMAGE) {
                    contentnew = "[图片]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TEXT
                        | imMessage.getMessageType() == Constant.MESSAGE_TYPR_APPLY_FRIEND
                        | imMessage.getMessageType() == Constant.MESSAGE_TYPR_BQEMOJI
                        | imMessage.getMessageType() == Constant.MESSAGE_TYPR_GROUP_TRANS_ME
                        | imMessage.getMessageType() == Constant.MESSAGE_GROUP_ADD_APPLY
                        | imMessage.getMessageType() == Constant.MESSAGE_TYPE_BE_JOIN_GROUP
                        | imMessage.getMessageType() == Constant.NOTICE_OF_APPLY_FRIEND
                        ) {
                    contentnew = imMessage.getContent();
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_ADD_GROUP) {
                    contentnew = "[有人加入了群]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_VOICE) {
                    contentnew = "[语音]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_LOCATION) {
                    contentnew = "[位置]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_REDPACKET_BACK) {
                    contentnew = "[您的红包被退还]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFRE_BACK) {
                    contentnew = "[您的转账被退还]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFRE_OK) {
                    contentnew = "[您的转账被领取]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_GET_REDPACKET) {
                    contentnew = "[您的红包被领取]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TRANSFRE) {
                    contentnew = "[转账]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_REDPACKTE) {
                    contentnew = "[红包]";
                } else if (imMessage.getMessageType() == Constant.Someone_initiated_the_lucky_red_envelope) {
                    contentnew = "[幸运红包]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_WITHDRAW) {
                    contentnew = "[撤回了一条消息]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_FILE) {//文件
                    contentnew = "[文件]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_VEDIO) {//小视屏
                    contentnew = "[小视屏]";
                   /* }else if (imMessage.getMessageType()==Constant.MESSAGE_TYPR_TRANSFOR_ISCOME){
                        contentnew = "[收款]";*/
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_TOPAYFOR) {
                    contentnew = "[付款]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_AAMONEY_GET) {
                    contentnew = "[AA收款]";
                } else if (imMessage.getMessageType() == Constant.Someone_initiated_the_lucky_red_envelope) {
                    contentnew = "[幸运红包]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPR_READ_DELETE) {
                    contentnew = "[阅后即焚]";
                } else if (imMessage.getMessageType() == Constant.MESSAGE_TYPE_INVATE_JOIN_GROUP) {
                    contentnew = "[邀请你加入群聊]";
                }
                ToolsUtils.notification(imMessage, contentnew);//第一次接收到消息时也要发送通知
            }

        }
        return messageEntivity;
    }

    /**
     * 设置置顶
     */
    private static void setTop(MessageEntivity messageEntivity) {
        List<TipEntity> tipEntities = TipEntity.find(TipEntity.class, "user_id=? and dest_id=?", messageEntivity.getFromid() + "", messageEntivity.getDestid() + "");
        //  for (int i = 0; i < tipEntities.size(); i++) {
        messageEntivity.setIstop(Constant.TOP_NOT_MAN);//默认不置顶
        if (tipEntities.size() > 0) {
            TipEntity tipEntity = tipEntities.get(0);
            if (tipEntity.getDestType() == Constant.FROM_TYPE_MAM) {
                if (("" + tipEntity.getDestId()).equals(messageEntivity.getDestid() + "") && ("" + tipEntity.getUserId()).equals(messageEntivity.getFromid() + "")) {
                    //单人的是否是在置顶通知
                    messageEntivity.setIstop(Constant.TOP_MAN);
                } else {
                    messageEntivity.setIstop(Constant.TOP_NOT_MAN);
                }
            } else if (tipEntity.getDestType() == Constant.FROM_TYPE_GROUP) {
                if (("" + tipEntity.getDestId()).equals(messageEntivity.getDestid() + "") && ("" + tipEntity.getUserId()).equals(messageEntivity.getFromid() + "")) {
                    //群聊的是否是在置顶通知
                    messageEntivity.setIstop(Constant.TOP_MAN);
                } else {
                    messageEntivity.setIstop(Constant.TOP_NOT_MAN);
                }
            }
        }
    }

    public static synchronized CircleEntivity ImMessageToCircleEntivity(ImMessage imMessage, int fromtype) {
        CircleEntivity circleEntivity = new CircleEntivity();
        circleEntivity.setType(imMessage.getType());
        circleEntivity.setNick(imMessage.getFromname());
        //  circleEntivity.setMessageNum();
        return null;

    }

    //朋友圈动态暂时存在缓存中
    public static synchronized void saveCircleNum() {

    }

    //存动态
    public static synchronized CircleNums ImMessageToCircleNum(ImMessage imMessage) {
        String content = imMessage.getContent();
        Integer messageType = imMessage.getMessageType();
        String fromname = imMessage.getFromname();
        Long fromid = imMessage.getFromid();
        Long destid = imMessage.getDestid();
        String imageIconUrl = imMessage.getImageIconUrl();
        Long receiveTime = imMessage.getReceiveTime();
        Long sendTime = imMessage.getSendTime();

        CircleNums circleNums = new CircleNums();
        circleNums.setType(messageType);
        circleNums.setCreattime(sendTime);
        circleNums.setIsread("0");
        circleNums.setUnicid(ToolsUtils.getMyUserId());
        circleNums.setFromusername(fromname);
        circleNums.setFromuserimgurl(imageIconUrl);

        try {
            JSONObject object = new JSONObject(content);
            String feedId = object.getString("feedId");
            if (messageType != Constant.MESSAGE_TYPR_CIRCLE_PRASIE) {
                String msg = object.getString("msg");
                circleNums.setMsg(msg);
                String feedmsg = object.getString("msg");
                circleNums.setFeedmsg(feedmsg);
            }
            // String feedmsg = object.getString("feedmsg");

            String imgs = object.getString("imgs");
            circleNums.setImgurl(imgs);
            Log.i("info", "ImMessageToCircleNum: -----------------------feedId-" + feedId);
            circleNums.setFeedid(feedId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        circleNums.save();
        return circleNums;
    }
}
